package com.volunteer.controller.admin;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.volunteer.common.R;
import com.volunteer.entity.Activity;
import com.volunteer.entity.ActivityType;
import com.volunteer.service.ActivityService;
import com.volunteer.service.ActivityTypeService;
import com.volunteer.service.RegistrationService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import cn.hutool.core.util.StrUtil;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/admin/activity")
@AllArgsConstructor
public class AdminActivityController {

    private final ActivityService activityService;

    private final ActivityTypeService activityTypeService;

    private final RegistrationService registrationService;


    /**
     * 获取所有活动列表（分页）
     * @return 活动列表
     */
    @GetMapping("/list")
    public R<Page<Activity>> list(@RequestParam(defaultValue = "1") int pageNum,
                                  @RequestParam(defaultValue = "10") int pageSize,
                                  @RequestParam(required = false) String keyword) {

        // 创建查询条件
        LambdaQueryWrapper<Activity> queryWrapper = new LambdaQueryWrapper<>();

        // 如果有关键字，添加标题模糊查询
        if (StrUtil.isNotBlank(keyword)) {
            queryWrapper.like(Activity::getTitle, keyword);
        }
        // 按创建时间倒序排序
        queryWrapper.orderByDesc(Activity::getCreateTime);
        List<ActivityType> activityTypeList = activityTypeService.list();
        Map<Long, String> map = activityTypeList.stream().collect(Collectors.toMap(ActivityType::getId, ActivityType::getName));
        // 执行查询
        Page<Activity> page= new Page<>(pageNum, pageSize);
        Page<Activity> activityPage = activityService.page(page, queryWrapper);
        List<Activity> list = activityPage.getRecords().stream().peek(activity1 -> {
            activity1.setActivityTypeName(map.get(Long.valueOf(activity1.getActivityTypeId())));
            // 设置报名人数
            activity1.setSignUpNumber(registrationService.count(new LambdaQueryWrapper<com.volunteer.entity.Registration>()
                    .eq(com.volunteer.entity.Registration::getActivityId, activity1.getId())));
        }).collect(Collectors.toList());
        activityPage.setRecords(list);
        return R.ok(activityPage);
    }

    /**
     * 新增活动
     * @param activity 活动对象
     * @return 操作结果
     */
    @PostMapping("/add")
    public R<String> add(@RequestBody Activity activity) {
        activity.setStatus(1);
        activity.setCreatorId(StpUtil.getLoginIdAsLong());
        boolean success = activityService.save(activity);
        return success ? R.ok("新增成功") : R.fail("新增失败");
    }

    /**
     * 更新活动信息
     * @param activity 活动对象（含ID）
     * @return 操作结果
     */
    @PostMapping("/update")
    public R<String> update(@RequestBody Activity activity) {
        boolean success = activityService.updateById(activity);
        return success ? R.ok("更新成功") : R.fail("更新失败");
    }

    /**
     * 删除活动
     * @param id 活动ID
     * @return 操作结果
     */
    @DeleteMapping("/delete/{id}")
    public R<String> delete(@PathVariable Long id) {
        boolean success = activityService.removeById(id);
        return success ? R.ok("删除成功") : R.fail("删除失败");
    }

    /**
     * 根据ID查询活动详情
     * @param id 活动ID
     * @return 活动对象
     */
    @GetMapping("/get/{id}")
    public R<Activity> getById(@PathVariable Long id) {
        Activity activity = activityService.getById(id);
        return activity != null ? R.ok(activity) : R.fail("未找到该活动");
    }

    @PostMapping("/upload")
    public R<Map<String, String>> upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return R.fail("文件为空");
        }
        String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
        String uploadDir = "D:/upload/activity/";
        File dir = new File(uploadDir);
        if (!dir.exists()) dir.mkdirs();
        try {
            file.transferTo(new File(uploadDir + fileName));
            String url = "http://localhost:8888"+"/upload/activity/" + fileName;
            Map<String, String> data = new HashMap<>();
            data.put("url", url);
            return R.ok(data);
        } catch (IOException e) {
            return R.fail("上传失败");
        }
    }
}
